/*手风琴
 * @Author: kevin.huang 
 * @Date: 2018-07-21 12:28:05 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-01-09 23:45:06
 * Copyright (c): kevin.huang Released under MIT License
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['$B'], function (_$B) {
            return factory(global, _$B);
        });
    } else {
        if(!global["$B"]){
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    function _createItme(item) {
        var it = {
            header: $("<h6 class='k_accordion_header k_box_size'>" + item.name + "</h6>").appendTo(this.jqObj),
            body: $("<div class='k_accordion_body k_box_size'></div>").appendTo(this.jqObj).hide()
        };
        it.header.data("title", item.name);
        if (item.url && item.url !== "") {
            it.body.data("url", item.url).data("type", item.type ? item.type : 'iframe');
        }else if(item.content){
            it.body.append(item.content);
        }
        if (typeof this.opts.onCreate === "function") {
            this.opts.onCreate.call(it.body, item.name);
        }
        if (item.icon && item.icon !== "") {
            it.header.prepend("<i style='padding-right:4px' class='fa " + item.icon + "'></i>");
        }
        return it;
    }

    function _click(e) {
        var $t = $(this);
        var index = $t.data("index");
        var _this = $t.data("_this");
        if (index === _this.actived.index) {
            return;
        }
        var adjust = 0,
            toHide = _this.actived.body,
            toShow = _this.items[index].body,
            duration,
            easing,
            boxSizing = toShow.css("box-sizing"),
            total = toShow.show().outerHeight();
        _this.actived.header.removeClass("k_accordion_header_actived").children(".k_accordion_header_icon").children("i").removeClass(_this.opts.iconClsAct).addClass(_this.opts.iconCls);
        _this._retoreStyle(_this.actived.header);
        _this.items[index].header.addClass("k_accordion_header_actived").children(".k_accordion_header_icon").children("i").removeClass(_this.opts.iconCls).addClass(_this.opts.iconClsAct);
        _this.actived = _this.items[index];
        _this._setActivedStyle();
        toHide.animate(_this.hideProps, {
            duration: duration,
            easing: easing,
            step: function (now, fx) {
                fx.now = Math.round(now);
            }
        });
        toShow.hide().animate(_this.showProps, {
            duration: duration,
            easing: easing,
            complete: function () {
                _this._onOpened();
            },
            step: function (now, fx) {
                fx.now = Math.round(now);
                if (fx.attr !== "height") {
                    if (boxSizing === "content-box") {
                        adjust += fx.now;
                    }
                } else if (_this.opts.heightStyle !== "content") {
                    fx.now = Math.round(total - toHide.outerHeight() - adjust);
                    adjust = 0;
                }
            }
        });
    }

    function Accordion(jqObj, opts) {
        $B.extend(this, Accordion); //继承父类        
        this.jqObj = jqObj.addClass("k_box_size k_accordion_main_wrap");
        this.opts = $.extend(true, {
            heightStyle: 'auto',
            iconCls: 'fa-angle-double-right', //收起图标
            iconClsAct: 'fa-angle-double-down', //展开图标
            iconPositon: 'right', //图标位置
            iconColor: '#666666', //图标颜色
            fontStyle: {
                "font-size": "14px",
                "font-weight": "bold",
                "color": "#666666"
            }, //标题字体颜色、大小配置
            activedStyle: {
                "background": "#71B9EA",
                "color": "#FFFFFF",
                "iconColor": '#FFFFFF'
            }, //激活状态样式            
            accordionStyle: {
                "background": "#F6F6F6",
                "border": "1px solid #C5C5C5"
            }, //手风琴边框、颜色定义
        }, opts);
        if (typeof this.opts.width !== 'undefined') {
            this.jqObj.outerWidth(this.opts.width);
        }
        if (typeof this.opts.height !== 'undefined') {
            this.jqObj.outerHeight(this.opts.height);
        } else {
            this.jqObj.outerHeight(this.jqObj.parent().height());
        }
        this.hideProps = {
            "borderTopWidth": "hide",
            "borderBottomWidth": "hide",
            "paddingTop": "hide",
            "paddingBottom": "hide",
            "height": "hide"
        };
        this.showProps = {
            "borderTopWidth": "show",
            "borderBottomWidth": "show",
            "paddingTop": "show",
            "paddingBottom": "show",
            "height": "show"
        };
        this.items = {};
        var _this = this;
        this.actived = undefined;
        this.bodyHeight = 0;
        var wrapHeight = this.jqObj.height();
        var ml = "14";
        if (this.opts.iconPositon === "left") {
            ml = "0";
        }
        for (var i = 0, len = this.opts.items.length; i < len; ++i) {
            var item = this.opts.items[i];
            var it = _createItme.call(this, item);
            it.header.css(this.opts.fontStyle).css(this.opts.accordionStyle);
            it.body.css("border", this.opts.accordionStyle.border).css("border-top", "none").attr("_title", it.name);
            it["index"] = i;
            var headerH = it.header.outerHeight();
            wrapHeight = wrapHeight - headerH - parseInt(it.header.css("margin-top").replace("px", ""));
            this.items[i] = it;
            it.header.click(_click).data("index", i).data("_this", _this);
            if (this.opts.iconCls && this.opts.iconCls !== "") {
                var icon = $("<div style='margin-left:" + ml + "px;margin-right:12px;float:" + this.opts.iconPositon + ";' class='k_accordion_header_icon'><i class='fa " + this.opts.iconCls + "'></i></div>");
                if ((typeof item.actived === "boolean" && item.actived) || i === 0) {
                    this.actived = it;
                }
                icon.appendTo(it.header).css("color", this.opts.iconColor);
                var iconH = icon.height();
                var marginTop = (headerH - iconH) / 2;
                icon.css("margin-top", marginTop);
            }

        }
        this.bodyHeight = wrapHeight;
        this.actived.header.addClass("k_accordion_header_actived");
        this.actived.body.outerHeight(this.bodyHeight).show();
        this.actived.header.children(".k_accordion_header_icon").children("i").removeClass(this.opts.iconCls).addClass(this.opts.iconClsAct);
        Object.keys(this.items).forEach(function (key) {
            _this.items[key].body.outerHeight(_this.bodyHeight);
        });
        this._setActivedStyle();
        this._onOpened();
    }
    Accordion.prototype = {
        _onOpened: function () {
            if (typeof this.opts.onOpened === "function") {
                this.opts.onOpened.call(this.actived.body, this.actived.header.data("title"));
            }
            var opts = this.opts;
            var url = this.actived.body.data("url");
            if(!url){
                return ;
            }
            if(url.indexOf("?") > 0){
                url = url + "&_t_="+$B.generateMixed(5);
            }else{
                url = url + "?_t_="+$B.generateMixed(5);
            }
            if (url && this.actived.body.children().length === 0) {
                var type = this.actived.body.data("type");
                var $content = this.actived.body;
                var loading = $("<div style='padding-left:16px;'><i class='fa fa-cog fa-spin fa-1.6x fa-fw margin-bottom'></i>" + $B.config.loading + "</div>").appendTo($content);
                if (type === 'html') {
                    $B.htmlLoad({
                        target: $content,
                        url: url,
                        loaded: function () {
                            loading.remove();
                            if (typeof opts.onLoaded === 'function') {
                                opts.onLoaded.call($content, type);
                            }
                            $B.bindTextClear($content);
                        }
                    });
                } else if (type === 'iframe') {
                    var iframe = $("<iframe  frameborder='0' style='overflow:visible' scrolling='auto' width='100%' height='100%' src='' ></iframe>").appendTo($content.css('overflow', 'hidden'));
                    var ifr = iframe[0];
                    var ifrId = $B.getUUID();
                    iframe.attr({"name":ifrId,"id":ifrId});
                    iframe.on("load",function(){
                        loading.remove();                        
                        try {
                            var ifrBody = $(this.contentDocument.body);
                            ifrBody.append("<span id='_window_ifr_id_' style='display:none'>"+ifrId+"</span>");
                        } catch (ex) {}
                        if (typeof opts.onLoaded === 'function') {
                            opts.onLoaded.call($content);
                        }
                    });
                    ifr.src = url;
                } else { //json加载
                    var ajaxOpts = {
                        async: true,
                        url: url,
                        ok: function (message, data) {
                            if (typeof opts.onLoaded === 'function') {
                                opts.onLoaded.call($content, type, data);
                            }
                        },
                        final: function (res) {
                            loading.remove();
                        }
                    };
                    this.ajax(ajaxOpts);
                }
            }
        },
        _retoreStyle: function ($it) {
            $it.css(this.opts.fontStyle).css("background", this.opts.accordionStyle.background).children("i").css("color", this.opts.iconColor);
            $it.children().children("i").css("color", this.opts.iconColor);
        },
        _setActivedStyle: function () {
            this.actived.header.css(this.opts.activedStyle).children("i").css("color", this.opts.activedStyle.iconColor);
            this.actived.header.children().children("i").css("color", this.opts.activedStyle.iconColor);
            this.actived.body.css(this.opts.accordionStyle);
        }
    };
    $B["Accordion"] = Accordion;
    return $B["Accordion"];
}));